package com.baozun.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baozun.mapper.TUserMapper;
import com.baozun.model.TUser;
import com.baozun.model.TUserExample;
import com.baozun.model.TUserExample.Criteria;
import com.baozun.service.UserService;
import com.baozun.util.PageData;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private TUserMapper userMapper;

    @Override
    public void add(TUser bean) {
        if(StringUtils.isEmpty(bean.getStUserId())){
            bean.setStUserId(UUID.randomUUID().toString());
        }
        bean.setDtRegisteTime(new Date());
        userMapper.insert(bean);
    }

    @Override
    public TUser get(String id) {
        // TODO Auto-generated method stub
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(TUser bean) {
        bean.setDtUpdateTime(new Date());
        userMapper.updateByPrimaryKeyWithBLOBs(bean);
    }

    @Override
    public void delete(String stUserId) {
        // TODO Auto-generated method stub
        userMapper.deleteByPrimaryKey(stUserId);
    }

    @Override
    public PageData<TUser> getPageListByExample(TUserExample record, int pageSize, int currentPage) {
        record.setSize(pageSize);
        record.setStart(pageSize * (currentPage - 1));
        PageData<TUser> infoList = new PageData<TUser>();
        List<TUser> appendixList = userMapper.selectByExample(record);
        int count = userMapper.countByExample(record);
        infoList.addAll(appendixList);
        infoList.setPage(currentPage);
        infoList.setPages((count + pageSize - 1) / pageSize);
        infoList.setPageSize(pageSize);
        infoList.setTotalRecords(count);
        return infoList;
    }

    @Override
    public List<TUser> getList(TUserExample record) {
        // TODO Auto-generated method stub
        return userMapper.selectByExample(record);
    }

    @Override
    public TUser getByUsername(String stUsername) {
        // TODO Auto-generated method stub
        TUserExample record = new TUserExample();
        Criteria criteria = record.createCriteria();
        criteria.andStUsernameEqualTo(stUsername);
        record.or(criteria);
        List<TUser> userList = this.getList(record);
        TUser user = null;
        if (CollectionUtils.isNotEmpty(userList)) {
            user = userList.get(0);
        }
        return user;
    }

}
